package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import io.swagger.models.auth.In;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.web.ServerProperties;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    @Override
    public TurnoverReportVO getturnoverStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> list=new ArrayList<>();
        list.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            list.add(begin);
        }
        List<Double> listSum=new ArrayList<>();
        for(LocalDate date:list){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            map.put("status", Orders.COMPLETED);
            Double sum=orderMapper.sumByMap(map);
            sum= sum==null ? 0.0 : sum;
            listSum.add(sum);
        }

        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(list,","))
                .turnoverList(StringUtils.join(listSum,","))
                .build();
    }

    @Override
    public UserReportVO getuserStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> list=new ArrayList<>();
        list.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            list.add(begin);
        }
        //存放每天新增用户数量
        List<Integer> userList=new ArrayList<>();
        //总的用户数量
        List<Integer> sumuserList=new ArrayList<>();
        for (LocalDate date:list){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap();
            map.put("end",endTime);
            Integer totalUser=userMapper.countByMap(map);
            sumuserList.add(totalUser);
            map.put("begin",beginTime);
            Integer nowUser=userMapper.countByMap(map);
            userList.add(nowUser);
        }

        return UserReportVO.builder()
                .dateList(StringUtils.join(list,","))
                .newUserList(StringUtils.join(userList,","))
                .totalUserList(StringUtils.join(sumuserList,","))
                .build();
    }

    @Override
    public OrderReportVO getOrdersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> list=new ArrayList<>();
        list.add(begin);
        while (!begin.equals(end)){
            begin=begin.plusDays(1);
            list.add(begin);
        }

        //查询有效订单数和订单总数
        List<Integer> totalconut=new ArrayList<>();
        List<Integer> valiodCount=new ArrayList<>();

        for(LocalDate date:list){
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map=new HashMap();
            map.put("begin",beginTime);
            map.put("end",endTime);
            Integer toCount=orderMapper.countByMap(map);
            map.put("status", Orders.COMPLETED);
            Integer vaCount=orderMapper.countByMap(map);
            totalconut.add(toCount);
            valiodCount.add(vaCount);
        }
        //计算总订单数
        Integer totalOrderCount=totalconut.stream().reduce(Integer::sum).get();
        //计算有效订单数
        Integer valiodOrderCount=valiodCount.stream().reduce(Integer::sum).get();
        //计算订单完成率
        Double orderCompletionRate=0.0;
        if(totalOrderCount !=0){
            orderCompletionRate=(double)valiodOrderCount/totalOrderCount;
        }


        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(list,","))
                .orderCountList(StringUtils.join(totalconut,","))
                .validOrderCountList(StringUtils.join(valiodCount,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(valiodOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO getTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);
        List<String> namelist = salesTop10.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        List<Integer> numberlist = salesTop10.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(namelist,","))
                .numberList(StringUtils.join(numberlist,","))
                .build();
    }

    @Override
    public void exportBusinessDate(HttpServletResponse response) {
        LocalDate beginDate = LocalDate.now().minusDays(30);
        LocalDate endDate= LocalDate.now().minusDays(1);
        //1查询数据库，获取营业数据---查询最近30天的运营数据
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(beginDate, LocalTime.MIN),
                LocalDateTime.of(endDate, LocalTime.MAX));

        //通过POI将数据写入到excel中
        InputStream in= this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excel=new XSSFWorkbook(in);
            XSSFSheet sheet1 = excel.getSheet("sheet1");
            sheet1.getRow(1).getCell(1).setCellValue("时间："+beginDate+"至"+endDate);
            XSSFRow row = sheet1.getRow(3);
            row.getCell(2).setCellValue(businessData.getTurnover());
            row.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            row.getCell(6).setCellValue(businessData.getNewUsers());

            XSSFRow row1 = sheet1.getRow(4);
            row1.getCell(2).setCellValue(businessData.getValidOrderCount());
            row.getCell(4).setCellValue(businessData.getUnitPrice());

            //填充明细数据
            for(int i=0;i<30;i++){
                LocalDate date=beginDate.plusDays(i);
                BusinessDataVO businessData1 = workspaceService.getBusinessData(LocalDateTime.of(date, LocalTime.MIN),
                        LocalDateTime.of(date, LocalTime.MAX));

                row=sheet1.getRow(7+i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessData1.getTurnover());
                row.getCell(3).setCellValue(businessData1.getValidOrderCount());
                row.getCell(4).setCellValue(businessData1.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessData1.getUnitPrice());
                row.getCell(6).setCellValue(businessData1.getNewUsers());
            }

            //通过输出流对象输出到客户端浏览器
            ServletOutputStream out=response.getOutputStream();
            excel.write(out);

            out.close();
            excel.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
